package com.linmu.controller;

import cn.apiclub.captcha.Captcha;
import com.linmu.utils.CaptchaUtil;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName CaptchaController.java
 * @Description 验证码控制类
 * @createTime 2022年01月30日 20:56:00
 */
@RestController
@RequestMapping("captcha")
public class CaptchaController {

    final CaptchaUtil captchaUtil;

    public CaptchaController(CaptchaUtil captchaUtil) {
        this.captchaUtil = captchaUtil;
    }

    @RequestMapping(value = "getCaptcha", method = RequestMethod.GET, produces = MediaType.IMAGE_PNG_VALUE)
    public @ResponseBody byte[] getCaptcha(HttpServletResponse response) {
        // 验证码IDS
        String captchaUuid = UUID.randomUUID().toString();

        Captcha captcha = captchaUtil.createCaptcha(captchaUuid);

        //将验证码ID保存入cookie
        Cookie cookie = new Cookie("CaptchaID",captchaUuid);
        response.addCookie(cookie);

        //返回验证码图片
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(captcha.getImage(),"png",byteArrayOutputStream);
            return byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            return null;
        }
    }

    @RequestMapping(value = "checkCaptcha", method = RequestMethod.POST)
    public @ResponseBody boolean checkCaptcha( @CookieValue("CaptchaID") String captchaUuid, @RequestParam("captchaAns") String captchaAns) {
        return captchaUtil.checkCaptcha(captchaUuid,captchaAns);
    }


}
